package cn.tedu.sp06.filter;

import cn.tedu.sp01.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {

    //pre routing,post ,error
    @Override
    public String filterType() {
        //return "pre"
        return FilterConstants.PRE_TYPE;
    }
    //过滤器的顺序号
    @Override
    public int filterOrder() {
        //有5 个默认的过滤器,自己的过滤器加到末尾
        return 6;//可以加到return 1 ,或者 return 4等, 在此需要放在末尾
    }
    //判断针对当前请求是否要执行过滤代码
    //如果调用item-service,检查是否登陆
    //否则,不检查登陆,直接访问
    @Override
    public boolean shouldFilter() {
        //先获取当前请求的上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //当前请求调用的服务Id
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        //判断调用的是否是item-service服务
        return "item-service".equals(serviceId);//返回true, 则执行过滤代码,检查权限,false不检查权限
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //获得上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //得到request对象
        HttpServletRequest request = ctx.getRequest();
        //http://localhost:3001/item-service/?token=
        //接收token参数
        String token = request.getParameter("token");
        //如果没有token,阻止继续调用,直接返回响应
        if (StringUtils.isBlank(token)){
            //阻止继续调用
            ctx.setSendZuulResponse(false);
            //直接返回响应
            //JsonResult ---{code:1,msg:xxx,data:null}
            ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(JsonResult.err().code(400).msg("Not Login ,未登录!").toString());
        }
        return null;//当前zuul版本 ,返回值没有作用
    }
}
